package com.usian.comment.service.impl;

import com.usian.comment.feign.UserFeign;
import com.usian.comment.service.CommentRepayService;
import com.usian.model.comment.dtos.CommentRepayDto;
import com.usian.model.comment.dtos.CommentRepayLikeDto;
import com.usian.model.comment.dtos.CommentRepaySaveDto;
import com.usian.model.comment.pojos.ApComment;
import com.usian.model.comment.pojos.ApCommentRepay;
import com.usian.model.comment.pojos.ApCommentRepayLike;
import com.usian.model.comment.vo.ApCommentRepayVo;
import com.usian.model.common.dtos.ResponseResult;
import com.usian.model.common.enums.AppHttpCodeEnum;
import com.usian.model.user.pojos.ApUser;
import com.usian.utils.threadlocal.ThreadLocalUtils;
import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class CommentRepayServiceImpl implements CommentRepayService {
    @Autowired
    private UserFeign userFeign;

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public ResponseResult loadCommentRepay(CommentRepayDto dto) {
        if (dto == null || dto.getCommentId() == null) return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        if (dto.getMinDate() == null) dto.setMinDate(new Date());
        Integer userId = ThreadLocalUtils.getUser();
        Query query = Query.query(Criteria.where("commentId").is(dto.getCommentId()).and("createdTime").lt(dto.getMinDate())).limit(10)
                .with(Sort.by(Sort.Direction.DESC, "createdTime"));
        //回复列表
        List<ApCommentRepay> repayList = mongoTemplate.find(query, ApCommentRepay.class);
        if (userId != null) {
            List<String> repayIds = repayList.stream().map(r -> r.getId()).collect(Collectors.toList());
            Query query1 = Query.query(Criteria.where("authorId").is(userId).and("commentRepayId").in(repayIds));
            List<ApCommentRepayLike> myLikes = mongoTemplate.find(query1, ApCommentRepayLike.class);
            List<ApCommentRepayVo> repayVos = new LinkedList<>();
            for (ApCommentRepay commentRepay : repayList) {
                ApCommentRepayVo repayVo = new ApCommentRepayVo();
                BeanUtils.copyProperties(commentRepay, repayVo);
                repayVo.setOperation((short) 1);
                for (ApCommentRepayLike like : myLikes) {
                    if (like.getCommentRepayId().equals(commentRepay.getId())) {
                        repayVo.setOperation((short) 0);
                        break;
                    }
                }
                repayVos.add(repayVo);
            }
            return ResponseResult.okResult(repayVos);
        }
        return ResponseResult.okResult(repayList);
    }

    @Override
    public ResponseResult saveCommentRepay(CommentRepaySaveDto dto) {
        if (dto == null || dto.getCommentId() == null || StringUtils.isBlank(dto.getContent()) || (dto.getContent() != null && dto.getContent().length() > 140))
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        Integer userId = ThreadLocalUtils.getUser();
        if (userId == null) return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        ApUser user = userFeign.findUserById(userId);
        ApCommentRepay repay = new ApCommentRepay();
        repay.setAuthorId(userId);
        repay.setAuthorName(user.getName());
        repay.setCommentId(dto.getCommentId());
        repay.setContent(dto.getContent());
        repay.setLikes(0);
        repay.setCreatedTime(new Date());
        repay.setUpdatedTime(new Date());
        mongoTemplate.save(repay);
        //查评论信息
        ApComment comment = mongoTemplate.findById(dto.getCommentId(), ApComment.class);
        comment.setReply(comment.getReply() + 1);
        mongoTemplate.save(comment);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @Override
    public ResponseResult saveCommentRepayLike(CommentRepayLikeDto dto) {
        if (dto == null || dto.getCommentRepayId() == null || dto.getOperation() == null || (dto.getOperation() != null && dto.getOperation() != 0 && dto.getOperation() != 1))
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        Integer userId = ThreadLocalUtils.getUser();
        if (userId == null) return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        ApCommentRepay commentRepay = mongoTemplate.findById(dto.getCommentRepayId(), ApCommentRepay.class);
        if (commentRepay == null) return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        if (dto.getOperation() == 0) {
            ApCommentRepayLike apCommentRepayLike = new ApCommentRepayLike();
            apCommentRepayLike.setAuthorId(userId);
            apCommentRepayLike.setCommentRepayId(dto.getCommentRepayId());
            apCommentRepayLike.setOperation((short) 0);
            mongoTemplate.save(apCommentRepayLike);
            commentRepay.setLikes(commentRepay.getLikes() + 1);
        } else {
            ApCommentRepayLike one = mongoTemplate.findOne(Query.query(Criteria.where("authorId").is(userId).and("commentRepayId").is(dto.getCommentRepayId())), ApCommentRepayLike.class);
            if (one != null) {
                mongoTemplate.remove(one);
            }
            commentRepay.setLikes(commentRepay.getLikes() - 1 > -1 ? commentRepay.getLikes() - 1 : 0);
        }
        mongoTemplate.save(commentRepay);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
